import sys,os,time,serial,sqlite3
sys.stderr = sys.stdout
from PyQt4 import QtCore, QtGui
from telas import Ui_telas
from configdialog import Ui_config

from testador import Testador
from configuracoes import Configuracoes

from lista_comandos import Lista_Comandos
from time import sleep

from variaveisui import Variaveisui

from tabelaoem import Tabelaoem
from apptxt import AlteraApp
from variaveis import Variaveis

from linha_comando import Linha_comando
import binascii

class StartQt4(QtGui.QMainWindow):

    def keyPressEvent(self, event):
        if (event.key() == QtCore.Qt.Key_F1):
            self.ui.comandoSerial.selectAll()
            self.ui.comandoSerial.setFocus()
            
        elif (event.key() == QtCore.Qt.Key_F2):
            self.ui.comandoSSH.selectAll()
            self.ui.comandoSSH.setFocus()
            
        elif (event.key() == QtCore.Qt.Key_F3):
            self.fotaozin()
            
        elif (event.key() == QtCore.Qt.Key_F4):
            self.ui.useHex.setChecked(True)
            self.conversaomegapower()
            
        elif(event.key() == QtCore.Qt.Key_F5):
            self.ui.useDec.setChecked(True)
            self.conversaomegapower()
        
    def resizeEvent(self, evento):
        if evento.size().height() > evento.oldSize().height():
            self.ui.SaidaSerial.setMinimumHeight(self.height()-70)
            self.ui.SaidaSSH.setMinimumHeight(self.height()-70)
            self.ui.filtros.setMinimumHeight(self.height()-70)
        else:
            self.ui.SaidaSerial.setMinimumHeight(65)
            self.ui.SaidaSSH.setMinimumHeight(65)
            self.ui.filtros.setMinimumHeight(65)

    def closeEvent(self, closeevent):
        arquivo = open('teste.a','wb')
        arquivo.write( self.saveState(1) )
        arquivo.close()
        QtGui.QMainWindow.closeEvent(self, closeevent)

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_telas()
        self.ui.setupUi(self)
        self.nomedobanco = 'banco.db'

        self.setWindowIcon(QtGui.QIcon('icons/Caminhao.png'))

        QtCore.QObject.connect(self.ui.f1config, QtCore.SIGNAL("clicked()"), self.telaf1config)
        QtCore.QObject.connect(self.ui.f2config, QtCore.SIGNAL("clicked()"), self.telaf2config)
        
        QtCore.QObject.connect(self.ui.actionTimestampSerial, QtCore.SIGNAL("triggered()"), self.trocaTimestampSerial)
        QtCore.QObject.connect(self.ui.actionTimestampSSH, QtCore.SIGNAL("triggered()"), self.trocaTimestampSSH)
        
        QtCore.QObject.connect(self.ui.filtros, QtCore.SIGNAL("visibilityChanged(bool)"), self.ui.actionMostrarFiltros.setChecked)
        QtCore.QObject.connect(self.ui.actionMostrarFiltros, QtCore.SIGNAL("triggered()"), self.mostrafiltros)
        QtCore.QObject.connect(self.ui.actionConfigura, QtCore.SIGNAL("triggered()"), self.configuradialog)
        QtCore.QObject.connect(self.ui.actionSobre, QtCore.SIGNAL("triggered()"), self.sobre)
        QtCore.QObject.connect(self.ui.actionLimparSSH, QtCore.SIGNAL("triggered()"), self.ui.tssh.clear)
        QtCore.QObject.connect(self.ui.limparSerial, QtCore.SIGNAL("triggered()"), self.ui.tserial.clear)
        QtCore.QObject.connect(self.ui.actionSair,QtCore.SIGNAL("triggered()"),self.close_window)
        QtCore.QObject.connect(self.ui.conexSSH,QtCore.SIGNAL("triggered()"),self.conexssh)
        QtCore.QObject.connect(self.ui.conexSerial,QtCore.SIGNAL("triggered()"),self.conexserial)
        QtCore.QObject.connect(self.ui.actionManual,QtCore.SIGNAL("triggered()"),self.abrirmanual)
        QtCore.QObject.connect(self.ui.actionOut,QtCore.SIGNAL("triggered()"),self.abriroutoem)
        QtCore.QObject.connect(self.ui.fotaozin,QtCore.SIGNAL("triggered()"), self.fotaozin)

        self.tester = Testador()
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("alteraserial(PyQt_PyObject)"), self.atualizaSerial)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("alterassh(PyQt_PyObject)"), self.ui.tssh.inserir)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("connectsuccess()"), self.conectsucesso)
        QtCore.QObject.connect(self.tester, QtCore.SIGNAL("connectfailed(PyQt_PyObject)"), self.conectnsucesso)

        self.iconoff = QtGui.QIcon(":/new/prefix1/icons/conectar.png")
        self.iconon = QtGui.QIcon(":/new/prefix1/icons/desconectar.png")
        
        #GAMBI
        self.buffer1 = ''
        self.conectarssh()
        self.conectarserial()
        
        # self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.ui.SaidaSerial)
        # self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.ui.filtros)
        # self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.ui.SaidaSSH)
        
        #lista de "lugares onde da pra selecionar"
        self.listaDeLugaresSelecionaveis = []
        self.listaDeLugaresSelecionaveis.append(self.ui.tserial)
        self.listaDeLugaresSelecionaveis.append(self.ui.tssh)
        self.listaDeLugaresSelecionaveis.append(self.ui.tfiltro1)
        self.listaDeLugaresSelecionaveis.append(self.ui.tfiltro2)
        self.listaDeLugaresSelecionaveis.append(self.ui.comandoSerial)
        self.listaDeLugaresSelecionaveis.append(self.ui.comandoSSH)
        
        for item in self.listaDeLugaresSelecionaveis:
            if not isinstance(item,Linha_comando):
                QtCore.QObject.connect(item,QtCore.SIGNAL("cursorPositionChanged ()"),self.conversaomegapower)
            else:
                QtCore.QObject.connect(item, QtCore.SIGNAL("selectionChanged()"), self.conversaomegapower)
    
        try:
            arquivo = open('teste.a','rb')
            a = arquivo.read(  )
            arquivo.close()
            if self.restoreState(QtCore.QByteArray (a) , 1):
                print 'sucesso1'
        except Exception, e:
            print e
  
    def conexserial(self):
        if self.tester.conectadoSerial:
            self.desconectarserial()
        else:
            self.conectarserial()
    def conexssh(self):
        if self.tester.ssh.conectado:
            self.desconectarssh()
        else:
            self.conectarssh()
            
    
    def conversaomegapower(self):
        texto = '####'
        for item in self.listaDeLugaresSelecionaveis:
            if item.hasFocus():
                if isinstance(item,Linha_comando):
                    texto = str(item.selectedText())
                else:
                    texto = str(item.textCursor().selectedText())
                if len(texto) > 0:
                    try:
                        if self.ui.useHex.isChecked():
                            tbin = bin(int(texto,16))[2:]
                            tdec = int(texto,16)
                            thex = texto
                        else:
                            tbin = bin(int(texto))[2:]
                            tdec = texto
                            thex = hex(int(texto))[2:]
                    except Exception, e:
                        print "deu merda"
                        print e
                        tbin = tdec = thex = '####'
                    self.ui.tcbin.setText('b: '+str(tbin))
                    self.ui.tcdec.setText('d: '+str(tdec))
                    self.ui.tchex.setText('h: '+str(thex))
                break
                
         
        
    # gambiarra do arabori
    def fotaozin(self):
        if self.tester.conectadoSerial:
            self.tester.serial1.write("@@@")
            sleep(0.2)
            self.tester.serial1.write("@@@\r\n")
            sleep(0.2)
            self.tester.serial1.write("mask 0 ffff ffff\r\n")
            sleep(0.5)
            self.tester.serial1.write("exit\r\n")
    
    def trocaTimestampSerial(self):
        try:
            self.tester.trocaTimestampSerial()
        except:
            QtGui.QMessageBox.critical(self,'Erro!','Tem q tar conectado a parada!')
            self.ui.actionTimestampSerial.setChecked(True)

    def trocaTimestampSSH(self):
        try:
            self.tester.trocaTimestampSSH()
        except:
            QtGui.QMessageBox.critical(self,'Erro!','Tem q tar conectado a parada!')
            self.ui.actionTimestampSSH.setChecked(True)

    def gravatelainout(self):
        pass
        # conn = sqlite3.connect(self.nomedobanco)
        # c = conn.cursor()
        # c.execute("update posicaotela SET inout_x=%s, inout_y=%s, inout_h=%s, inout_w=%s,floating=%s, visible=%s, telameio=%s, rdSend=0 where id=2"
               # % (self.ui.filtros.x(), self.ui.filtros.y(), self.ui.filtros.height(), self.ui.filtros.width(),
                   # int(self.ui.filtros.isFloating()), int(self.ui.filtros.isVisible()),0)
               # )
        # conn.commit()
        # conn.close()
            
    def mostrafiltros(self):
        if self.ui.filtros.isVisible():
            self.ui.filtros.hide()
        else:
            self.ui.filtros.show()
            
    def abretelainout(self):
        pass
        # conn = sqlite3.connect(self.nomedobanco)
        # c = conn.cursor()
        # try:
            # c.execute("CREATE TABLE posicaotela (id INTEGER, inout_x INTEGER, inout_y INTEGER, inout_h INTEGER, inout_w INTEGER, floating INTEGER, visible INTEGER, telameio INTEGER, rdSend INTEGER)")
            # conn.commit()
        # except Exception, err:
            # print err
            # pass
            
        # c = conn.cursor()
        # try:
            # c.execute("INSERT INTO posicaotela VALUES (2,0,0,0,0,0,0,1,0)")
            # conn.commit()
        # except Exception, err:
            # print err
            # pass

        # c.execute("select * from posicaotela where id=2")
        # linha = c.fetchall()
        # print linha
        # for x in linha:
            # self.ui.filtros.setFloating(bool(x[5]))
            # self.ui.filtros.setGeometry(x[1], x[2], x[4], x[3] )
            # if x[6]:
                # self.ui.filtros.show()
            # else:
                # self.ui.filtros.close()
                
        # conn.close()
                
    def apptxt(self):
        if self.tester.ssh.conectado:
            txt = AlteraApp(self, self.tester.ssh.transport)
            txt.show()
                
    def abrirappoem(self):
        self.abriroem('OEMApplication.txt')

    def abriroutoem(self):
        self.abriroem('OEMOutputs.txt')

    def abriroem(self,oem):
        if self.tester.ssh.conectado:
            tab = Tabelaoem(self,self.tester.ssh.transport,oem)
            tab.show()

    def abrirmanual(self):
        os.startfile(os.getcwd() + '/Manual/Manual.pdf')
       
    def conectsucesso(self):
        self.ui.tssh.append("OK")
        self.ui.conexSSH.setIcon(self.iconon)
        self.tester.conectarrastrear()

    def conectnsucesso(self, msg):
        QtGui.QMessageBox.critical(self,'Erro!','Nao foi possivel estabelecer a conexao com o servidor:\n'+str(msg))

    def conectarssh(self):
        self.ui.tssh.append('\nConectando...')
        self.tester.conectarssh()
        self.ui.actionTimestampSSH.setChecked(True)

    def desconectarssh(self):
        self.ui.tssh.append('\nDesconectando...')
        self.tester.desconectarssh()
        self.ui.conexSSH.setIcon(self.iconoff)
    
    def atualizaFiltros(self, filtro, tfiltro, texto):
        textos, cores = filtro.carregar()
        for i in xrange(len(textos)):
            if textos[i].upper() in texto.upper():
                tf1 = '<font color=' +cores[i]+ '>' +texto.replace(' ','&nbsp;')+ '</font>'
                tfiltro.append(tf1)
            
    def atualizaSerial(self, texto):
        f1 = Variaveis('filtro1')
        f2 = Variaveis('filtro2')
        txt = (self.buffer1+texto).split('\n')
        for i in xrange(len(txt)-1):
            self.atualizaFiltros(f1,self.ui.tfiltro1,txt[i])
            self.atualizaFiltros(f2,self.ui.tfiltro2,txt[i])
        self.buffer1 = txt[-1]

        self.ui.tserial.inserir(texto.replace('\r',''))

    def configuradialog(self):
        config = Configuracao(self)
        config.setModal(True)
        config.show()

    def sobre(self):
        about = Sobre(self)
        about.show()

    def close_window(self):
        exit()
        
    def conectarserial(self):
        self.ui.tserial.append('Conectando...')
        try:
            self.tester.conectarserial()
            self.ui.tserial.append('OK')
            self.ui.actionTimestampSerial.setChecked(True)
            self.ui.conexSerial.setIcon(self.iconon)
        except (Exception), porta:
            QtGui.QMessageBox.critical(self,'Erro!',('Nao foi possivel conectar o serial'))
            self.ui.tserial.append('FALHOU')

    def desconectarserial(self):
        self.ui.tserial.append('\nDesconectando...')
        self.tester.desconectarserial()
        self.ui.conexSerial.setIcon(self.iconoff)
    
    def enviarComandoSSH(self):
        comando = str(self.ui.comandoSSH.text())
        self.ui.comandoSSH.addcommand(comando)
        if self.tester.ssh.conectado:
            self.tester.ssh.enviaComando(comando)
        self.ui.comandoSSH.clear()
        
    def enviarComandoSerial(self):
        comando = str(self.ui.comandoSerial.text())
        self.ui.comandoSerial.addcommand(comando)
        if self.tester.conectadoSerial:
            if comando == '+++' or comando == '@@@':
                self.tester.serial1.write(comando)
            else:
                for c in comando:
                    self.tester.serial1.write(c)
                self.tester.serial1.write('\r')
        self.ui.comandoSerial.clear()

    def telaf1config(self):
        telaVars = Variaveisui('filtro1',self)
        telaVars.show()

    def telaf2config(self):
        telaVars = Variaveisui('filtro2',self)
        telaVars.show()
# --------------------------- FIM testerui --------------------

from aboutdialog import Ui_Dialog

class Sobre(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

class Configuracao(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_config()
        self.ui.setupUi(self)
        self.config = Configuracoes()
        self.ui.serverssh.insert(self.config.ssh_ip)
        self.ui.portassh.insert(self.config.ssh_porta)
        self.ui.loginssh.insert(self.config.ssh_login)
        self.ui.senhassh.insert(self.config.ssh_senha)
        self.ui.portarvs.insert(self.config.rvs_porta)
        self.ui.protocolorvs.insert(self.config.rvs_protocolo)
        self.ui.comandorvs.insert(self.config.rvs_comando)
        self.ui.velocidade.insert(self.config.ser_speed)
        self.ui.portaserial_2.insert(self.config.ser_porta)
        
        if self.config.use_proxy == '1':
            self.ui.checkBox.setChecked(True)
        else:
            self.ui.radioButton.setEnabled(False)
            self.ui.radioButton_2.setEnabled(False)
            self.ui.radioButton_3.setEnabled(False)
            self.ui.label_9.setEnabled(False)
            self.ui.label_11.setEnabled(False)
            self.ui.lineEdit_2.setEnabled(False)
            self.ui.lineEdit.setEnabled(False)
            self.ui.label_12.setEnabled(False)
            self.ui.lineEdit_3.setEnabled(False)
            self.ui.label_13.setEnabled(False)
            self.ui.lineEdit_4.setEnabled(False)
        if self.config.proxytype == '1':
            self.ui.radioButton.setChecked(True)
        elif self.config.proxytype == '2':
            self.ui.radioButton_2.setChecked(True)
        else:
            self.ui.radioButton_3.setChecked(True)
            
        self.ui.lineEdit.insert(self.config.proxyaddr)
        self.ui.lineEdit_2.insert(self.config.proxylogin)
        self.ui.lineEdit_3.insert(self.config.proxysenha)
        self.ui.lineEdit_4.insert(self.config.proxyport)

        QtCore.QObject.connect(self.ui.portaserial,QtCore.SIGNAL("accepted()"),self.salva)
        QtCore.QObject.connect(self.ui.checkBox,QtCore.SIGNAL("stateChanged(int)"),self.a)

    def a(self,st):
        state = bool(st)
        self.ui.radioButton.setEnabled(state)
        self.ui.radioButton_2.setEnabled(state)
        self.ui.radioButton_3.setEnabled(state)
        self.ui.label_9.setEnabled(state)
        self.ui.label_11.setEnabled(state)
        self.ui.lineEdit_2.setEnabled(state)
        self.ui.label_12.setEnabled(state)
        self.ui.lineEdit_3.setEnabled(state)
        self.ui.label_13.setEnabled(state)
        self.ui.lineEdit_4.setEnabled(state)
        self.ui.lineEdit.setEnabled(state)
        
    def salva(self):
        self.config.ssh_ip = str(self.ui.serverssh.text())
        self.config.ssh_porta = str(self.ui.portassh.text())
        self.config.ssh_login = str(self.ui.loginssh.text())
        self.config.ssh_senha = str(self.ui.senhassh.text())
        self.config.rvs_porta = str(self.ui.portarvs.text())
        self.config.rvs_protocolo = str(self.ui.protocolorvs.text())
        self.config.rvs_comando = str(self.ui.comandorvs.text())
        self.config.ser_porta = str(self.ui.portaserial_2.text())
        self.config.ser_speed = str(self.ui.velocidade.text())
        
        if self.ui.radioButton.isChecked():
            self.config.proxytype = 1
        elif self.ui.radioButton_2.isChecked():
            self.config.proxytype = 2
        else:
            self.config.proxytype = 3
            
        self.config.use_proxy = int(self.ui.checkBox.isChecked())
        self.config.proxyaddr = str(self.ui.lineEdit.text())
        self.config.proxylogin = str(self.ui.lineEdit_2.text())
        self.config.proxysenha = str(self.ui.lineEdit_3.text())
        self.config.proxyport= str(self.ui.lineEdit_4.text())

        self.config.gravar()

#-----------------------------------------------------
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = StartQt4()
    myapp.show()
    sys.exit(app.exec_())
